/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author volodymyr.sadovyy
 */
package com.vs.MobiFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InvalidObjectException;

public class MobiFile {

    private File f;
    private String pdbheader;
    private String mobiheader;
    private final int mobiHeaderOffset;
    private final int mobiHeaderLength;
    
    private final int titleOffcet;
    private final int titleLength;
    private final String title;


	public MobiFile() throws Exception {
        throw new Exception("not implemented");
    }

    public MobiFile(File aFile) throws IOException {
        f = aFile;

        FileInputStream fis = new FileInputStream(f);
        
        //TODO: Fix this stupid data type cast
        int size = (int)f.length();

        byte[] buff = new byte[size];
        StringBuilder contentSTR = new StringBuilder();
        byte[] contentBYTE = new byte[10240];
        boolean first = true;
        while (fis.read(buff) != -1) {
            contentSTR.append(new String(buff));
            if (first) {
                contentBYTE = buff.clone();
                first = false;
            }
        }

        pdbheader = new String(contentBYTE).substring(0, HeaderConstants.PALM_DB_HEADER_LENGTH);
        if (!pdbheader.substring(HeaderConstants.PALM_DB_HEADER_IDENTIFICATOR_ADDRESS,
                HeaderConstants.PALM_DB_HEADER_IDENTIFICATOR_ADDRESS + HeaderConstants.PALM_DB_HEADER_IDENTIFICATOR_LENGTH).equals(HeaderConstants.PALM_DB_HEADER_IDENTIFICATOR_MOBI)) {
            throw new InvalidObjectException("This is not valid MOBI file");
        }
        
        

        mobiheader = new String(contentBYTE).substring(HeaderConstants.PALM_DB_HEADER_LENGTH);
        mobiHeaderOffset = mobiheader.indexOf(HeaderConstants.MOBI_HEADER_IDENTIFICATOR) - 16 + HeaderConstants.PALM_DB_HEADER_LENGTH;
        mobiHeaderLength = get4Hex(contentBYTE, mobiHeaderOffset + HeaderConstants.MOBI_HEADER_LENGTH_ADDRESS); 

        titleOffcet = get4Hex(contentBYTE, 
        		mobiHeaderOffset + HeaderConstants.MOBI_HEADER_TITLE_ADDRESS);
        titleLength = get4Hex(contentBYTE, 
        		mobiHeaderOffset + HeaderConstants.MOBI_HEADER_TITLE_LENGTH_ADDRESS);
        title = new String(contentBYTE, 
        		titleOffcet + mobiHeaderOffset, titleLength, "UTF8");

    }

	private int get4Hex(byte[] content, int offcet) {
		return ((content[offcet] & 0xFF) << 24) | 
				((content[offcet + 1] & 0xFF) << 16) | 
				((content[offcet + 2] & 0xFF) << 8) | 
				content[offcet + 3] & 0xFF;
	}

    public MobiFile(String aFileName) throws IOException {
        this(new File(aFileName));

    }

	public int getHeaderLength() {
		return mobiHeaderLength;
	}
    public String getTitle() {
		return title;
	}
}
